<template>
	<a-modal
		v-model:visible="modalVisible"
		@ok="handleCrop"
		@cancel="modalVisible = false; options.img = ''"
	>
		<template #title> 图片裁剪 </template>
		<VueCropper
			ref="cropperRef"
			:mode="options.contain"
			:img="options.img"
			:output-size="options.size"
			:full="options.full"
			:output-type="options.outputType"
			:original="options.original"
			:can-move-box="options.canMoveBox"
			:info="true"
			:fixed="options.fixed"
			:auto-crop="options.autoCrop"
			:autoCropWidth="options.autoCropWidth"
			:autoCropHeight="options.autoCropHeight"
		>
		</VueCropper>
	</a-modal> 
</template>
<script lang="ts" setup>
import { uploadFileCommon } from "@/api/common/index";
import { base64toFile } from "@/utils/file";
import "vue-cropper/dist/index.css";
import { VueCropper } from "vue-cropper";
const cropperRef = ref(null);
const modalVisible = ref(false);
const emit = defineEmits(["handleUpload"]);
const options = ref<any>({
	mode: "contain", // 图片默认渲染方式
	img: "", // 上传图片地址
	size: 1, // 输出图片大小
	full: true, // 是否输出原图比例的截图
	outputType: "png", // 输出图片格式
	original: false, // 上传图片按照原始比例渲染
	canMoveBox: true, // 截图框能否拖动
	fixed: true,
	autoCrop: true, // 是否默认生成截图框
	fixedNumber: [1, 1],
	autoCropWidth: "350", // 输出图片宽高
	autoCropHeight: "350" // 输出图片宽高
});

// 裁剪
const handleCrop = () => {
	cropperRef.value.getCropData(async (data) => {
		const formData = new FormData();
		formData.append("file", base64toFile(data));
		try {
			const res = await uploadFileCommon(formData);
			emit("handleUpload", res.data);
			modalVisible.value = false;
			options.value.img = "";
		} catch (err) {
			console.log(err);
		}
	});
};
defineExpose({
	options,
	modalVisible
});
</script>
<style lang="scss" scoped>
.vue-cropper {
	width: 100% !important;
	height: 400px;
}
</style>
